package com.cuotigou.util;


import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.request.FieldAnalysisRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.AnalysisResponseBase;
import org.apache.solr.client.solrj.response.FieldAnalysisResponse;
import org.apache.solr.client.solrj.response.QueryResponse;


import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * Created by Administrator on 2019/1/30.
 */
public class SolrUtil {

    public static  HttpSolrServer server;

    static  {
        String url = "http://ctgadmin.scjapp.cn:8888/solr";
        server = new HttpSolrServer(url);
        server.setMaxRetries(1); // defaults to 0. > 1 not recommended.  
        server.setConnectionTimeout(5000);// 5 seconds to establish TCP  

        server.setParser(new XMLResponseParser());// binary parser is used by  

        server.setSoTimeout(1000);// socket read timeout  
        server.setDefaultMaxConnectionsPerHost(100);
        server.setMaxTotalConnections(100);
        server.setFollowRedirects(false);// defaults to false  
        server.setAllowCompression(true);

    }

    public static void solrAdd() {

        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id",2 );
        doc.addField("keyword","加法");
        try {
            server.add(doc);
            server.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void delete() {
        //删除文档
        try {
            server.deleteById("1");
            server.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void select() {
        //2.创建查询语句
        SolrQuery query = new SolrQuery();
        //3.设置查询条件
        query.set("q", "keyword:加法");
        //4.执行查询
        QueryResponse queryResponse = null;
        try {
            queryResponse = server.query(query);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        //5.取文档列表public class SolrDocumentList extends ArrayList<SolrDocument>
        SolrDocumentList documentList = queryResponse.getResults();
        for (SolrDocument solrDocument : documentList) {
            //取各个文档信息
            System.out.println("商品id:"+solrDocument.get("id")+" ");
            System.out.println("商品标题:"+solrDocument.get("keyword")+" ");
        }
    }

    /**
     * 获取分词
     * @param sentence
     * @return
     */
    public static List<String> getAnalysis(String sentence) {
        FieldAnalysisRequest request = new FieldAnalysisRequest(
                "/analysis/field");
        request.addFieldName("keyword");// 字段名，随便指定一个支持中文分词的字段
        request.setFieldValue("");// 字段值，可以为空字符串，但是需要显式指定此参数
        request.setQuery(sentence);

        FieldAnalysisResponse response = null;
        try {
            response = request.process(server);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> results = new ArrayList<String>();
        Iterator<AnalysisResponseBase.AnalysisPhase> it = response.getFieldNameAnalysis("keyword")
                .getQueryPhases().iterator();
        while(it.hasNext()) {
            AnalysisResponseBase.AnalysisPhase pharse = (AnalysisResponseBase.AnalysisPhase)it.next();
            List<AnalysisResponseBase.TokenInfo> list = pharse.getTokens();
            for (AnalysisResponseBase.TokenInfo info : list) {
                results.add(info.getText());
            }
        }

        return results;
    }

    public static void getAnalysis() {
        List<String> results = getAnalysis("加法减法除法平均数+加法减法除法平均数");
        for (String word : results) {
            System.out.println(word);
        }
    }

    public static void main(String[] args) {
//        solrAdd();
//        delete();
//        select();
        getAnalysis();
    }

}
